package com.ezcolour.ticket.admin.controller;

import com.ezcolour.ticket.base.BaseController;
import static com.ezcolour.ticket.bean.HttpKit.getIp;
import com.ezcolour.ticket.common.log.LogManager;
import com.ezcolour.ticket.common.log.factory.LogTaskFactory;
import com.ezcolour.ticket.common.shiro.ShiroKit;
import com.ezcolour.ticket.common.shiro.ShiroUser;
import com.ezcolour.ticket.common.util.KaptchaUtil;
import com.ezcolour.ticket.model.User;
import com.ezcolour.ticket.service.UserService;
import com.ezcolour.ticket.util.ToolUtil;
import com.google.code.kaptcha.Constants;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        //获取菜单列表
        List<Long> roleList = ShiroKit.getUser().getRoleList();
        if (roleList == null || roleList.size() == 0) {
            ShiroKit.getSubject().logout();
            model.addAttribute("tips", "该用户没有角色，无法登陆");
            return "/admin/login";
        }


        //获取用户头像
        Long id = ShiroKit.getUser().getId();
        User user = userService.findById(id);
        String avatar = user.getAvatar();
        model.addAttribute("avatar", avatar);

        return  "/admin/index";
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (ShiroKit.isAuthenticated() || ShiroKit.getUser() != null) {
            return REDIRECT + ADMINPREFIX+ "/";
        } else {
            return  "/admin/login";
        }
    }

    /**
     * 跳转到欢迎页面
     */
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String welcome() {
        if (ShiroKit.isAuthenticated() || ShiroKit.getUser() != null) {
            return  "/admin/welcome";
        } else {
            return  "/admin/login";
        }
    }

    /**
     * 点击登录执行的动作
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginVali() {

        String username = super.getPara("username").trim();
        String password = super.getPara("password").trim();
        String remember = super.getPara("remember");

        //验证验证码是否正确
        if (KaptchaUtil.getKaptchaOnOff()) {
            String kaptcha = super.getPara("kaptcha").trim();
            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
                //throw new InvalidKaptchaException();
            }
        }

        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());

        if ("on".equals(remember)) {
            token.setRememberMe(true);
        } else {
            token.setRememberMe(false);
        }

        currentUser.login(token);

        ShiroUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());

        //LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), getIp()));

        ShiroKit.getSession().setAttribute("sessionFlag", true);

        return REDIRECT + ADMINPREFIX+ "/";
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logOut() {
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), getIp()));
        ShiroKit.getSubject().logout();
        return REDIRECT + ADMINPREFIX +"/login";
    }
}
